import { Injectable, NotFoundException, BadRequestException, InternalServerErrorException } from '@nestjs/common';
import { CreateAuthDto } from './dto/create-auth.dto';
// 注入 NV_UsersRepository
import { NV_Users, UserRole } from './entities/user.entity';
import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import * as bcryptjs from "bcryptjs"
import { JwtService } from "@nestjs/jwt"
import { UpdateRoleDto } from './dto/update-auth.dto';
import { UserDetails } from './entities/user.detail.entity';
import * as uuid from 'uuid';
import { UpdateUserDetailDto } from './dto/update-auth-detail.dto';
import { generateUniqueId } from 'src/utils/upique_id';

@Injectable()
export class AuthService {
  jwtBlacklistService: any;
  constructor(
    @InjectRepository(NV_Users)
    private readonly user: Repository<NV_Users>,
    @InjectRepository(UserDetails)
    private readonly UserDetails: Repository<UserDetails>,
    private readonly JwtService: JwtService,
  ) {}

  // 测试
  async findOne(id: any): Promise<any> {
    // 输入验证
    if (typeof id !== 'number' || isNaN(id)) {
      throw new BadRequestException({
        status: 400,
        message: '无效的 ID 参数',
      });
    }
    try {
      const data = await this.getDataById(id);
      if (!data) {
        throw new NotFoundException({
          status: 404,
          message: '数据未找到',
        });
      }
      const processedData = this.processData(data);
      return {
        data: processedData,
        status: 200,
        message: '数据获取成功'
      };
    } catch (error) {
      if (error.response?.status) {
        throw error;
      } else {
        throw new InternalServerErrorException({
          status: 500,
          message: '服务端错误',
        });
      }
    }
  }
  private async getDataById(id: number): Promise<any> {
    // 模拟从数据库或其他来源获取数据
    return id === 1 ? { id, name: 'Sample Data' } : null;
  }

  private processData(data: any): any {
    // 数据处理逻辑
    return {
      ...data,
      processed: true
    };
  }

  // 注册
  async signup(signupData: CreateAuthDto) {
    console.log('signupData', signupData)
    // 1. 检查用户名是否已经存在
    const existingUser = await this.user.findOne({
      where: { username: signupData.username },
    });
    if (existingUser) {
      throw new BadRequestException({
        statusCode: 400,
        message: '用户名已存在',
      });
    }
    const userId = `user_${generateUniqueId(10)}`;

    // 2. 对密码进行加密处理
    const hashedPassword = bcryptjs.hashSync(signupData.password, 10);
    signupData.password = hashedPassword;
    // 3. 保存用户数据到数据库中
    try {
      const newUser = this.user.create({
        ...signupData,
        role: UserRole.User, // 默认user角色
        user_id: userId,
      });
      await this.user.save(newUser);
       // 创建 UserDetails 并关联到用户
       const userDetails = this.UserDetails.create({
         user: newUser,
         user_id: userId,
      });
      await this.UserDetails.save(userDetails);
      
      // 4. 返回成功的响应
      return {
        status: 200,
        message: '注册成功',
      };
    } catch (error) {
      throw new InternalServerErrorException({
        statusCode: 500,
        message: '用户注册失败，请稍后再试',
      });
    }
  }

  // 登录
  async login(loginData: CreateAuthDto) {
    // 1. 查找用户是否存在
    const user = await this.user.findOne({
      where: { username: loginData.username },
    });
    console.log('user',user)
    if (!user) {
      throw new BadRequestException('不存在该用户');
    }
    // 2. 验证密码
    const isPasswordValid = bcryptjs.compareSync(loginData.password, user.password);
    if (!isPasswordValid) {
      throw new BadRequestException('用户名或密码不正确');
    }
    // 3. 生成并返回 JWT
    const payload = { username: user.username, sub: user.id, role: user.role }; // 包含角色
    const token = this.JwtService.sign(payload);

    return {
      data: { token, role: user.role, user_id: user.user_id }, // 返回角色信息
      status: 200,
      message: '登录成功',
    };
  }

  // 更新用户角色
  async updateRole(id: number, updateRoleDto: UpdateRoleDto) {
    // 查找用户
    const user = await this.user.findOneBy({ id });
    if (!user) {
      throw new NotFoundException({
        status: 404,
        message: '用户未找到',
      });
    }
    // 更新用户角色
    user.role = updateRoleDto.role;
    try {
      await this.user.save(user);
      return {
        status: 200,
        message: '用户角色更新成功',
      };
    } catch (error) {
      throw new InternalServerErrorException({
        status: 500,
        message: '更新用户角色失败，请稍后再试',
      });
    }
  }

  // 退出登录
  async logout(jwtPayload: any) {
    // 你可以添加一些逻辑来处理注销，例如清除服务器上的黑名单令牌
    // 但是对于 JWT，通常客户端负责删除令牌
    try {
      const token = `JWT-${jwtPayload.sub}`;
      await this.addToBlacklist(token);
      return {
        status: 200,
        message: '退出登录成功',
      };
    } catch (error) {
      throw new InternalServerErrorException({
        status: 500,
        message: '退出登录失败，请稍后再试',
      });
    }
  }
  private async addToBlacklist(token: string): Promise<void> {
    // 这里应该是添加到黑名单的逻辑，比如存储到数据库或Redis
    // 以下代码仅为示例，实际实现需要根据你的应用程序需求来编写
    console.log(`Token added to blacklist: ${token}`);
    // 假设黑名单存储操作
  }

  // 获取用户详情
  async getUserDetailById(userId: string): Promise<any> {
    if (typeof userId !== 'string' || !userId.startsWith('user_')) {
      throw new BadRequestException({
        status: 400,
        message: '无效的 user_id 参数',
      });
    }
    try {
      const userDetail = await this.UserDetails.findOne({
        where: { user_id: userId },
        relations: ['user'], // 加载 User 实体
      });
      if (!userDetail) {
        throw new NotFoundException({
          status: 404,
          message: '用户详情未找到',
        });
      }
      let { id, user_id, firstName, lastName, image_url } = userDetail
      return {
        data: { id, user_id, firstName, lastName, image_url },
        status: 200,
        message: '数据获取成功'
      };
    } catch (error) {
      if (error.response?.status) {
        throw error;
      } else {
        throw new InternalServerErrorException({
          status: 500,
          message: '服务端错误',
        });
      }
    }
  }
  // 更新用户详情
  async updateUserDetailById(userId: string, updateUserDetailDto: UpdateUserDetailDto): Promise<any> {
    if (typeof userId !== 'string' || !userId.startsWith('user_')) {
      throw new BadRequestException({
        status: 400,
        message: '无效的 user_id 参数',
      });
    }
    try {
      const userDetail = await this.UserDetails.findOne({
        where: { user_id: userId },
        relations: ['user'], // 加载 User 实体
      });
      if (!userDetail) {
        throw new NotFoundException({
          status: 404,
          message: '用户详情未找到',
        });
      }
      Object.assign(userDetail, updateUserDetailDto);
      await this.UserDetails.save(userDetail);
      return {
        status: 200,
        message: '用户信息更新成功',
      };
    } catch (error) {
      if (error.response?.status) {
        throw error;
      } else {
        throw new InternalServerErrorException({
          status: 500,
          message: '服务端错误',
        });
      }
    }
  }
  // 删除用户详情
  async deleteUserDetailById(userId: string): Promise<any> {
    if (typeof userId !== 'string' || !userId.startsWith('user_')) {
      throw new BadRequestException({
        status: 400,
        message: '无效的 user_id 参数',
      });
    }

    try {
      const userDetail = await this.UserDetails.findOne({
        where: { user_id: userId },
      });

      if (!userDetail) {
        throw new NotFoundException({
          status: 404,
          message: '用户详情未找到',
        });
      }
      // 删除用户详情
      await this.UserDetails.delete(userDetail.id);
      return {
        status: 200,
        message: '用户信息删除成功'
      };

    } catch (error) {
      if (error.response?.status) {
        throw error;
      } else {
        throw new InternalServerErrorException({
          status: 500,
          message: '服务端错误',
        });
      }
    }
  }
} 